package com.yinhai.message.client.api;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;

import com.yinhai.message.api.bean.TMMessage;
import com.yinhai.message.api.bean.TMAppMessage;
import com.yinhai.message.api.bean.TMUser;
import com.yinhai.message.api.bean.TMWeChat;
import com.yinhai.message.api.exception.TMException;
import com.yinhai.message.api.vo.TMMessageVo;
import com.yinhai.message.client.tool.HttpPoolManager;
import com.yinhai.message.client.tool.TMSendValidate;

/**
 * 提供第第三方应用调用消息操作的实现类  httpapi
 *
 * @author yanglq 2017.3.28
 */
public class TMHttpService implements ITMService {

    private static TMHttpService tmHttpService = null;
    private static Properties properties = null;

    public synchronized static TMHttpService getInstance() throws Exception {
        if (tmHttpService == null) {
            tmHttpService = new TMHttpService();
            properties = new Properties();
            properties.load(TMHttpService.class.getClassLoader().getResourceAsStream("TaMessage.properties"));
        }
        return tmHttpService;
    }

    @Override
    public String sendMessage(TMUser sendUser, TMUser receiveUser, TMMessage tmMessage, TMWeChat wechat) throws Exception {
        List<TMUser> receiveUserList = new ArrayList<>();
        receiveUserList.add(receiveUser);
        return sendMessage(sendUser, receiveUserList, tmMessage, wechat);
    }

    @Override
    public String sendMessage(TMUser sendUser, List<TMUser> receiveUserList,
                              TMMessage tmMessage, TMWeChat wechat) throws Exception {
        TMSendValidate.validateInfo(sendUser, receiveUserList, tmMessage);
        TMMessageVo vo = new TMMessageVo(sendUser, receiveUserList, tmMessage, "", wechat);
        return sendMessageWithApi(vo);
    }

    @Override
    public String sendMessage(TMUser sendUser, List<TMUser> receiveUserList, TMMessage tmMessage, TMWeChat wechat, boolean useMime) throws Exception {
        TMSendValidate.validateInfo(sendUser, receiveUserList, tmMessage);
        TMMessageVo vo = new TMMessageVo(sendUser, receiveUserList, tmMessage, "", wechat);
        return sendMessageWithApi(vo, useMime);
    }

    @Override
    public List<TMMessage> getTMMessage(TMUser user, Date start, Date end) throws Exception {
        return null;
    }

    String sendMessageWithApi(TMMessageVo vo) throws Exception {
        //CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpClient client = HttpPoolManager.getHttpClient();
        Properties properties = new Properties();
        properties.load(this.getClass().getClassLoader().getResourceAsStream("TaMessage.properties"));
        String ticket = properties.getProperty("ticket");
        vo.setTicket(ticket);
        String msgCenterAddr = properties.getProperty("msgCenterAddr");
        if (msgCenterAddr.lastIndexOf("/") != -1) {
            msgCenterAddr += "/";
        }
        String path = msgCenterAddr + "messageHttp/messageHttpController!sendMessage.do";
        HttpPost post = new HttpPost(path);
        String content = com.alibaba.fastjson.JSON.toJSONString(vo);
        MultipartEntityBuilder reqEntitybuilder = MultipartEntityBuilder.create();
        reqEntitybuilder.addTextBody("ticket", ticket);
        reqEntitybuilder.addTextBody("msgjsonstr", content, ContentType.create("text/plain", Charset.forName("UTF-8")));
        List<File> files = vo.getMessage().getFiles();
        if (files != null)
            for (File file : files) {
                reqEntitybuilder.addBinaryBody("file", file, ContentType.create("application/json"), file.getName());
            }
        HttpEntity entity = reqEntitybuilder.build();
        post.setEntity(entity);
        CloseableHttpResponse response = client.execute(post);
        InputStream is = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        is.close();
        response.close();
        return sb.toString();
    }

    @Override
    public String sendAppMessage(String aac001, TMAppMessage messageApp) throws Exception {
        if (aac001 == null || "".equals(aac001)) {
            throw new TMException("aac001  为空");
        }
        CloseableHttpClient client = HttpPoolManager.getHttpClient();
        String msgCenterAddr = properties.getProperty("msgCenterAddr");
        if (msgCenterAddr.lastIndexOf("/") != -1) {
            msgCenterAddr += "/";
        }
        String path = msgCenterAddr
                + "messageHttp/messageHttpController!sendAppMessage.do";
        HttpPost post = new HttpPost(path);
        String content = com.alibaba.fastjson.JSON.toJSONString(messageApp);
        MultipartEntityBuilder reqEntitybuilder = MultipartEntityBuilder
                .create();
        reqEntitybuilder.addTextBody("aac001", aac001,
                ContentType.create("text/plain", Charset.forName("UTF-8")));
        reqEntitybuilder.addTextBody("msgjsonstr", content,
                ContentType.create("text/plain", Charset.forName("UTF-8")));

        HttpEntity entity = reqEntitybuilder.build();
        post.setEntity(entity);
        CloseableHttpResponse response = client.execute(post);
        InputStream is = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        is.close();
        response.close();
        return sb.toString();
    }

    /**
     * 提供给 低版本MIME 的兼容方法
     */
    String sendMessageWithApi(TMMessageVo vo, boolean useMime) throws Exception {
        CloseableHttpClient client = HttpPoolManager.getHttpClient();
        Properties properties = new Properties();
        properties.load(this.getClass().getClassLoader().getResourceAsStream("TaMessage.properties"));
        String ticket = properties.getProperty("ticket");
        vo.setTicket(ticket);
        String msgCenterAddr = properties.getProperty("msgCenterAddr");
        if (msgCenterAddr.lastIndexOf("/") != -1) {
            msgCenterAddr += "/";
        }
        String path = msgCenterAddr + "messageHttp/messageHttpController!sendMessage.do";
        HttpPost post = new HttpPost(path);
        String content = com.alibaba.fastjson.JSON.toJSONString(vo);
		/*JSONObject json = new JSONObject();
		json.put("ticket",ticket);
		json.put("msgjsonstr",content);*/
        StringEntity stringEntity = new StringEntity("ticket=" + ticket + "&msgjsonstr=" + content, "UTF-8");
//		post.addHeader("Content-type", "application/json; charset=utf-8");
        post.addHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
        post.setEntity(stringEntity);
        CloseableHttpResponse response = client.execute(post);
        InputStream is = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        is.close();
        response.close();
        return sb.toString();
    }
}
